package openase.audiosearch;

import java.util.ArrayList;
import java.util.List;

import openase.audio.AudioFingerprint;
import openase.audio.Storage;
import openase.audio.StorageException;
import openase.audiosearch.ranking.AudioRanking;
import openase.audiosearch.ranking.RankingStrategy;


public class AudioSearchFacade {

	// the returned AudioRanking[] has the same size as the strategies[] informed
	public static AudioRanking[] search(AudioFingerprint[] fps, RankingStrategy[] strategies) throws StorageException {
		final AudioRanking[] rankings = new AudioRanking[strategies.length];

		List<FingerprintMatch> matchesList = new ArrayList<FingerprintMatch>();

		final Storage storage = Storage.getStorage();
		for (AudioFingerprint fpQuery : fps) {
			AudioFingerprint[] matchingFingerprints = storage.getMatchingFingerprints(fpQuery.getHash());
			addMatches(matchesList, fpQuery, matchingFingerprints);
		}

		final FingerprintMatch[] matches = matchesList.toArray(new FingerprintMatch[0]);
		matchesList = null;// let GC work

		for (int i = 0; i < strategies.length; i++) {
			RankingStrategy rs = strategies[i];
			final AudioRanking rank = rs.rank(matches);
			rankings[i] = rank;
		}

		return rankings;
	}

	private static void addMatches(List<FingerprintMatch> matchesList, AudioFingerprint query, AudioFingerprint[] matchingFingerprints) {
		for (AudioFingerprint repositoryFp : matchingFingerprints) {
			matchesList.add(new FingerprintMatch(query, repositoryFp));
		}

	}

}
